/*
 * timecost.h
 *
 *  Created on: 2021/3/10
 *      Author: hailiang
 */

#ifndef TIMECOST_H
#define TIMECOST_H

#include <absl/strings/str_format.h>
#include <absl/time/clock.h>

class TimeCost {

public:
    TimeCost() {
        restart();
    }

    void restart() {
        start_     = absl::Now();
        is_finish_ = false;
    }

    void finish() {
        end_       = absl::Now();
        duration_  = end_ - start_;
        is_finish_ = true;
    }

    double costInSecond() {
        if (!is_finish_) {
            finish();
        }

        return absl::ToDoubleSeconds(duration_);
    }

    std::string costInSecond(const std::string &header) {
        auto cost = costInSecond();
        return absl::StrFormat("%s %0.6lf seconds", header.c_str(), cost);
    }

    double costInMillisecond() {
        if (!is_finish_) {
            finish();
        }
        return absl::ToDoubleMilliseconds(duration_);
    }

    std::string costInMillisecond(const std::string &header) {
        auto cost = costInMillisecond();
        return absl::StrFormat("%s %0.3lf milliseconds", header.c_str(), cost);
    }

private:
    absl::Time     start_, end_;
    absl::Duration duration_;

    bool is_finish_;
};

#endif // TIMECOST_H
